package com.glory.brepda.adapter;

import static com.glory.brepda.utils.ShowDialog.showImagePreviewDialog;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Base64;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;

import androidx.annotation.Nullable;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.glory.brepda.R;
import com.glory.brepda.base.MyApp;
import com.glory.brepda.entity.QCCheckBean;
import com.glory.brepda.utils.FileUtils;
import com.glory.brepda.utils.SmbFileUtils;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralPop;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_PopUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import jcifs.smb.SmbFile;

public class QCDetailCheckAdapter extends BaseQuickAdapter<QCCheckBean.QCFORMDTO.ITEMLINESDTO, BaseViewHolder> {

    private List<String> mResultList;
    private FreeUI_GeneralPop mCheckResultPop;
    private OnUploadClickListener uploadClickListener;

    public QCDetailCheckAdapter(@Nullable List<QCCheckBean.QCFORMDTO.ITEMLINESDTO> data,OnUploadClickListener listener) {
        super(R.layout.adapter_qc_detail,data);
        this.uploadClickListener = listener;
        mResultList = new ArrayList<>();
        mResultList.add("OK");
        mResultList.add("NG");
    }

    @Override
    protected void convert(BaseViewHolder helper, QCCheckBean.QCFORMDTO.ITEMLINESDTO item) {

        helper.setText(R.id.tvCheckName,item.getITEM_NAME());
        helper.setText(R.id.tvCheckResult,item.getRESULT_FLAG());
        helper.setText(R.id.etValue,item.getRESULT());
        // 设置默认值"OK"如果RESULT为空
        if (item.getRESULT() == null || item.getRESULT().isEmpty()) {
            helper.setText(R.id.etValue, "OK");
            item.setRESULT("OK");
        } else {
            helper.setText(R.id.etValue, item.getRESULT());
        }
        setEditListener(helper.getView(R.id.etValue),item);
        FrameLayout flCheckResult = helper.getView(R.id.flCheckResult);
        flCheckResult.setOnClickListener(view -> {
            mCheckResultPop = FreeApi_PopUtils.getNormalPop(MyApp.app, flCheckResult.getWidth(), mResultList, helper.getView(R.id.ivCheckResult), (code, i) -> {
                item.setRESULT_FLAG(code);
                helper.setText(R.id.tvCheckResult,code);
            });
            FreeApi_PopUtils.setArrowShow(helper.getView(R.id.ivCheckResult));
            mCheckResultPop.showAsDropDown(flCheckResult, 0, 0);
        });
        helper.getView(R.id.upImage).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (uploadClickListener != null) {
                    uploadClickListener.onUploadClick(helper.getAdapterPosition());
                }
            }
        });

        if (item.getANNEX_URL_LIST().size()>0){
            helper.setText(R.id.upImage, "追加");
        }


//        String annexUrl = item.getANNEX_URL();
//        if (!TextUtils.isEmpty(annexUrl)) {
//            helper.setText(R.id.upImage, "更换");
//
//            ImageView showImage = helper.getView(R.id.showImage);
//
//            if (isBase64(annexUrl)) {
//                try {
//                    byte[] decodedBytes = Base64.decode(annexUrl, Base64.DEFAULT);
//                    Bitmap decodedBitmap = BitmapFactory.decodeByteArray(decodedBytes, 0, decodedBytes.length);
//                    showImage.setImageBitmap(decodedBitmap);
//                } catch (Exception e) {
//                    e.printStackTrace(); // 可选：日志
//                }
//            } else if (annexUrl.startsWith("\\\\")) {
//                // 异步加载 SMB 文件
//                String localDir = FileUtils.getLocalPathAndFileName(MyApp.app);
//                String smbPath = SmbFileUtils.downLoadImage + annexUrl.substring(annexUrl.lastIndexOf("\\") + 1);
//                new Thread(() -> {
//                    boolean success = SmbFileUtils.smbGet(smbPath, localDir);
//                    if (success) {
//                        try {
//                            SmbFile remoteFile = new SmbFile(smbPath);
//                            String fileName = remoteFile.getName();
//                            File imageFile = new File(localDir + File.separator + fileName);
//
//                            if (imageFile.exists()) {
//                                Bitmap bitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
//
//                                showImage.post(() -> {
//                                    if (annexUrl.equals(showImage.getTag())) {
//                                        showImage.setImageBitmap(bitmap);
//                                    }
//                                });
//                            }
//                        } catch (Exception e) {
//                            e.printStackTrace();
//                        }
//                    }
//                }).start();
//            }
//        }


//        helper.getView(R.id.showImage).setOnClickListener(v -> {
//            String base64 = item.getANNEX_URL();
//            if (base64 == null || base64.isEmpty()) {
//                return;
//            }
//            showImagePreviewDialog(helper.itemView.getContext(), base64);
//        });

    }


    private void setEditListener(EditText editText, QCCheckBean.QCFORMDTO.ITEMLINESDTO item) {
        if (editText.getTag() instanceof TextWatcher) {
            editText.removeTextChangedListener((TextWatcher) editText.getTag());
        }

        TextWatcher watcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                item.setRESULT(s.toString());
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        };

        editText.addTextChangedListener(watcher);
        editText.setTag(watcher);
    }


    public interface OnUploadClickListener {
        void onUploadClick(int position);
    }

    public static boolean isBase64(String str) {
        // 判断字符串是否只包含 Base64 合法字符并且长度是4的倍数
        return str.matches("^[A-Za-z0-9+/=\\r\\n]+$") && str.length() % 4 == 0;
    }


}
